<template>
  <div :class="containerClass">
    <pre v-if="type === 'block'" :class="codeBlockClass"><code v-html="highlightedCode"></code></pre>
    <code v-else :class="codeBlockClass" v-html="highlightedCode"></code>
  </div>
</template>

<script setup>
import { computed, ref, watch, onMounted } from 'vue';
import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript';
import xml from 'highlight.js/lib/languages/xml';
import css from 'highlight.js/lib/languages/css';
import json from 'highlight.js/lib/languages/json';
import bash from 'highlight.js/lib/languages/bash';
import plaintext from 'highlight.js/lib/languages/plaintext';

// 仅注册需要的语言以减小打包体积
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('xml', xml);
hljs.registerLanguage('css', css);
hljs.registerLanguage('json', json);
hljs.registerLanguage('bash', bash);
hljs.registerLanguage('text', plaintext);


const props = defineProps({
  code: {
    type: String,
    required: true,
  },
  language: {
    type: String,
    default: 'text',
  },
  type: {
    type: String,
    default: 'block',
    validator: (value) => ['inline', 'block'].includes(value),
  },
  showLineNumbers: {
    type: Boolean,
    default: false,
  },
});

const highlightedCode = ref('');

const containerClass = computed(() => [
  'axiom-code-container',
  `axiom-code-container--${props.type}`,
  { 'axiom-code--line-numbers': props.showLineNumbers && props.type === 'block' },
]);

const codeBlockClass = computed(() => [
  'axiom-code',
  `language-${props.language}`
]);

// 核心功能：高亮代码
const highlight = () => {
  if (!props.code) {
    highlightedCode.value = '';
    return;
  }
  try {
    const language = hljs.getLanguage(props.language) ? props.language : 'text';
    const result = hljs.highlight(props.code, { language, ignoreIllegals: true });
    highlightedCode.value = result.value;
  } catch (e) {
    console.error('AxiomCode Highlight Error:', e);
    // 在高亮失败时回退到纯文本
    highlightedCode.value = props.code.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  }
};

// 侦听 code 和 language 属性的变化，重新执行高亮
watch(() => [props.code, props.language], highlight, { immediate: true });

</script>

<style lang="scss" scoped>
@use '../../styles/components/common/axiom-code';
</style> 